<template>
  <div>
    <BasicTable @register="register" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <a-button @click="handleCreate" type="primary" v-if="hasPermission(['system:dept:create'])">
          新增
        </a-button>
        <a-button @click="expandAll">全部展开</a-button>
        <a-button @click="collapseAll">全部折叠</a-button>
      </template>
      <template #leader="{ text }">
        <span> {{ userNicknameFormat(text) }} </span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: handleEdit.bind(null, record),
              ifShow: hasPermission(['system:dept:update']),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              ifShow: hasPermission(['system:dept:delete']),
              popConfirm: {
                title: '是否删除数据？',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <DeptModal @register="registerModal" @success="reload()" />
  </div>
</template>
<script lang="ts" setup>
  import { nextTick, ref, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import DeptModal from './components/DeptModal.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { deleteDept, getDeptList } from '/@/api/backs/system/dept';
  import { columns, searchFormSchema } from './tableData';
  import { userSelect } from '/@/api/backs/system/user';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const { hasPermission } = usePermission();
  let userOptions: any[] = [];

  async function getUserList() {
    try {
      const res = await userSelect({});
      userOptions = res;
    } catch (error) {}
  }
  const [register, { expandAll, collapseAll, reload, setColumns }] = useTable({
    title: '组织架构列表',
    api: getDeptList,
    columns,
    formConfig: { labelWidth: 120, schemas: searchFormSchema },
    isTreeTable: true,
    pagination: true,
    useSearchForm: true,
    striped: false,
    showTableSetting: true,
    showIndexColumn: false,
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
  });
  const users = ref<any[]>([]);

  // async function getUserList() {
  //   const res = await userSelect;
  //   users.value = res;
  // }

  function handleCreate() {
    openModal(true, { isUpdate: false });
  }

  function handleEdit(record: Recordable) {
    openModal(true, { record, isUpdate: true });
  }

  async function handleDelete(record: Recordable) {
    await deleteDept({ id: record.id });
    createMessage.success('删除成功！');
    reload();
  }

  function onFetchSuccess() {
    getUserList();
    columns[1] = {
      title: '负责人',
      dataIndex: 'leaderUserId',
      width: 120,
      customRender: ({ text }) => {
        if (!text) {
          return '未设置';
        }
        for (const user of userOptions) {
          if (text === user.id) {
            return user.nickname;
          }
        }
      },
    };
    setColumns(columns);
    nextTick(expandAll);
  }

  function userNicknameFormat(row) {
    if (!row.leaderUserId) {
      return '未设置';
    }
    for (const user of users.value) {
      if (row.leaderUserId === user.id) {
        return user.nickname;
      }
    }
    return '未知【' + row.leaderUserId + '】';
  }

  onMounted(async () => {
    // await getUserList();
  });
</script>
